
import { jwtDecode } from "jwt-decode";
import Cookies from 'js-cookie'

export default {
    ACCESS_TOKEN: "ACCESS-TOKEN",
    REFRESH_TOKEM: "REFRESH-TOKEN",
    USER_DATA: "USER-DATA",

    saveToken(access, refresh, remember){
        // 解析令牌
        let accessToken = jwtDecode(access);
        // 解析刷新令牌
        let refreshToken = jwtDecode(refresh);

        let accessDuration = accessToken.exp - refreshToken.iat;
        let refreshDuration = refreshToken.exp - refreshToken.iat;

        // 获取 访问令牌 的 过期 时间
        Cookies.set(this.ACCESS_TOKEN, access, {expires: accessDuration / (24 * 60 * 60)});

        if (remember){
            Cookies.set(this.REFRESH_TOKEM, refresh, {expires: refreshDuration / (24 * 60 * 60)});
        }else {
            // 设置 会话Cookie , 随浏览器 的关闭而销毁
            Cookies.set(this.REFRESH_TOKEM, refresh);
        }
        // 存储用户 的基本信息
        let {user_id, name, tel, roleName, className} = accessToken;
        
        // 将数据转成json
        let jsonstr = JSON.stringify({user_id, name, tel, roleName, className});

        // 将中文转码
        jsonstr = encodeURI(jsonstr);
        // console.log(jsonstr);
        localStorage.setItem(this.USER_DATA, btoa(jsonstr));
    },
    getCurrentUser(){
        let data = localStorage.getItem(this.USER_DATA);

        // console.log(data);
        if (data == null){
            return {};
        }
        // 使用 base64 解码
        let jsonstr = decodeURI(atob(data));

        // 转成json对象
        return JSON.parse(jsonstr);
    }
    // existsRefreshToken(){

    // }

}

